package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BaseException;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collections;
import java.util.Date;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;        //Spring容器
    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public String upload(MultipartFile file) throws IOException {
        //获取文件名的后缀
        String extension = FileUploadUtils.getExtension(file);
        //判断传入的格式是否符合   equalsIgnoreCase 忽略大小写
        if (!"bpmn".equalsIgnoreCase(extension)) {
            throw new BaseException("请输入正确格式");
        }
        // filePath 文件
        String filePath = FileUploadUtils.upload(SystemConfig.getProfile(), file);
        return filePath;
    }

    @Override
    public void deploy(String path, String bpmnType, String info) throws IOException {
        //获取之前上传的文件
        FileInputStream stream =new  FileInputStream(new File(SystemConfig.getProfile(),path));
        //将文件部署到Activit7中
        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(path, stream)
                .deploy();
        //释放资源
        stream.close();
        //封装bpmnInfo的信息
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setDeployTime(new Date());
        bpmnInfo.setInfo(info);
        bpmnInfo.setBpmnType(bpmnType);             //审核类型,数据字典的值
        bpmnInfo.setDeploymentId(deploy.getId());   //部署ID
        //获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfoMapper.insert(bpmnInfo);

    }

    @Override
    public InputStream getFileInputStream(String deploymentId, String type) {
        InputStream inputStream = null;
        //获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        if ("xml".equalsIgnoreCase(type)) {
            //获取xml文件
            String resourceName = processDefinition.getResourceName();      //获取流程定义列的值
            inputStream = repositoryService.getResourceAsStream(deploymentId,resourceName);
        }else {
            //获取png文件
            //仓库获取 bpmnModel 给到 generator
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();    //生成图片的处理类
            //generateDiagram(bpmn模型,需要高亮节点ID集合,,需要高亮节点ID集合)
            inputStream = generator.generateDiagram(bpmnModel,
                    Collections.EMPTY_LIST,
                    Collections.EMPTY_LIST,
                    "宋体",
                    "宋体",
                    "宋体"
                    );
        }
        return inputStream;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        String deploymentId = bpmnInfo.getDeploymentId();
        //TODO 查询所有的流程实例,找到业务标识,更新业务标识

        //删除bpmnInfo
        bpmnInfoMapper.deleteByPrimaryKey(id);
        //根据流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        //删除流程定义
        repositoryService.deleteDeployment(deploymentId,true);

        //找到资源名称
        String resourceName = processDefinition.getResourceName();
        //SystemConfig.getProfile()前缀  resourceName 路径  构建 file文件
        File file = new File(SystemConfig.getProfile(),resourceName);
        //判断 file 是否存在
        if (file.exists()) {
            file.delete();
        }
    }

    @Override
    public BpmnInfo getByBpmnType(String bpmnType) {
        return bpmnInfoMapper.getByBpmnType(bpmnType);
    }

    @Override
    public BpmnInfo get(Long bpmnInfoId) {
        return bpmnInfoMapper.selectByPrimaryKey(bpmnInfoId);
    }
}

